<template>
  <div class="pay-page">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>确认支付</h2>
        <button @click="goBack" class="btn btn-secondary">
          <i class="fa fa-arrow-left mr-2"></i>返回
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载支付信息中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="alert alert-danger mt-3">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 支付信息表单 -->
    <div v-if="!loading && !errorMessage" class="card mt-4">
      <div class="card-body">
        <h4 class="card-title">支付信息</h4>
        <div class="pay-info">
          <p><strong>支付类型:</strong> {{ payType === 'deposit' ? '定金' : '执行款' }}</p>
          <p><strong>合同名称:</strong> {{ contractName }}</p>
          <p><strong>支付金额:</strong> <span class="amount">{{ amount }}</span> 元</p>
          <p><strong>付款计划ID:</strong> {{ paymentPlanId }}</p>
        </div>

        <!-- 支付按钮 -->
        <button
            @click="confirmPay"
            class="btn btn-primary w-100 mt-4"
            :disabled="payLoading"
        >
          <i class="fa fa-credit-card mr-2"></i>
          <span v-if="!payLoading">确认支付</span>
          <span v-if="payLoading">支付中...</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'PayPage',
  setup() {
    const route = useRoute()
    const router = useRouter()

    // 接收路由参数（从原页面传递）
    const paymentPlanId = ref(route.query.paymentPlanId || '')
    const payType = ref(route.query.payType || 'deposit') // deposit/execution

    // 支付信息
    const contractName = ref('')
    const amount = ref('0.00')
    const loading = ref(true)
    const errorMessage = ref('')
    const payLoading = ref(false)

    // 加载支付详情（调用后端接口获取金额、合同名称等）
    const fetchPayDetail = () => {
      if (!paymentPlanId.value) {
        errorMessage.value = '缺少付款计划ID，无法支付'
        loading.value = false
        return
      }

      // 调用后端接口获取支付详情（复用原有接口，避免新增）
      axios.get(`/api/payment-plans/${paymentPlanId.value}`)
          .then(res => {
            const data = res.data
            contractName.value = data.contractName
            amount.value = data.amount
          })
          .catch(err => {
            errorMessage.value = `加载支付信息失败: ${err.response?.data?.message || err.message}`
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 确认支付（调用后端支付接口，与原逻辑兼容）
    const confirmPay = () => {
      payLoading.value = true
      errorMessage.value = ''

      // 调用原支付接口（与后端PaymentService.createPay兼容）
      axios.post('/api/pay', { paymentPlanId: paymentPlanId.value })
          .then(payRes => {
            // 跳转支付宝支付页面（与原逻辑一致）
            document.write(payRes.data)
          })
          .catch(err => {
            errorMessage.value = `支付请求失败: ${err.response?.data?.message || err.message}`
            payLoading.value = false
          })
    }

    // 返回原页面
    const goBack = () => {
      router.back()
    }

    onMounted(() => {
      fetchPayDetail()
    })

    return {
      paymentPlanId,
      payType,
      contractName,
      amount,
      loading,
      errorMessage,
      payLoading,
      fetchPayDetail,
      confirmPay,
      goBack
    }
  }
}
</script>

<style scoped>
.header {
  background-color: #f8f9fa;
  padding: 15px;
  border-bottom: 1px solid #dee2e6;
}
.header-content {
  max-width: 1200px;
  margin: 0 auto;
}
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
}
.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}
@keyframes spin {
  to { transform: rotate(360deg); }
}
.pay-info {
  margin: 20px 0;
  line-height: 2;
}
.amount {
  color: #dc3545;
  font-weight: bold;
  font-size: 1.2em;
}
</style>